#include <string.h>
#include <errno.h>
#include <stdio.h>
#include <signal.h>
#ifndef _WIN32
#include <netinet/in.h>
# ifdef _XOPEN_SOURCE_EXTENDED
#  include <arpa/inet.h>
# endif
#include <sys/socket.h>
#endif

#include <event2/bufferevent.h>
#include <event2/buffer.h>
#include <event2/listener.h>
#include <event2/util.h>
#include <event2/event.h>

static const char MESSAGE[] = "Hello, World!\n";

static const int PORT = 9995;

static void listener_cb(struct evconnlistener *, evutil_socket_t,
                        struct sockaddr *, int socklen, void *);
static void conn_writecb(struct bufferevent *, void *);
static void conn_readcb(struct bufferevent *, void *);
static void conn_eventcb(struct bufferevent *, short, void *);
static void signal_cb(evutil_socket_t, short, void *);

/**
 * libevent 使用
 *      创建 event_base 根节点
 *      初始化上树节点
 *      节点上树
 *      节点下树
 *      删除节点
 *      释放 event_base 根节点
 *
 * bufferevent
 *      应用层会有 一个文件描述符，两个缓冲区 三个回调（读回调，写回调，事件回调）
 *      流程：
 *          创建 event_base 根节点
 *          创建一个新的节点
 *          设置节点对应文件描述符触发事件的回调，设置结束就上树了
 *          设置事件 是否 可用
 *          循环监听
 *
 * gcc main.c -levent -o server
 * @return
 */
int
main(int argc, char **argv)
{
    struct event_base *base;
    struct evconnlistener *listener;
    struct event *signal_event;

    struct sockaddr_in sin = {0};
#ifdef _WIN32
    WSADATA wsa_data;
	WSAStartup(0x0201, &wsa_data);
#endif

    // 创建根节点
    base = event_base_new();
    // 判断一下是否成功
    if (!base) {
        fprintf(stderr, "Could not initialize libevent!\n");
        return 1;
    }

    sin.sin_family = AF_INET;
    sin.sin_port = htons(PORT);

    // 创建链接侦听器
    listener = evconnlistener_new_bind(base, listener_cb, (void *)base,
                                       LEV_OPT_REUSEABLE|LEV_OPT_CLOSE_ON_FREE, -1,
                                       (struct sockaddr*)&sin,
                                       sizeof(sin));

    if (!listener) {
        fprintf(stderr, "Could not create a listener!\n");
        return 1;
    }

    // 创建信号 触发节点
    signal_event = evsignal_new(base, SIGINT, signal_cb, (void *)base);

    // 信号节点上树
    if (!signal_event || event_add(signal_event, NULL)<0) {
        fprintf(stderr, "Could not create/add a signal event!\n");
        return 1;
    }

    // 循环监听
    event_base_dispatch(base);

    // 释放链接侦听器
    evconnlistener_free(listener);
    // 释放信号节点
    event_free(signal_event);
    // 释放根节点
    event_base_free(base);

    printf("done\n");
    return 0;
}

static void
listener_cb(struct evconnlistener *listener, evutil_socket_t fd,
            struct sockaddr *sa, int socklen, void *user_data)
{
    struct event_base *base = user_data;
    struct bufferevent *bev;

    // 将fd上树
    // 新建一个bufferevent节点
    bev = bufferevent_socket_new(base, fd, BEV_OPT_CLOSE_ON_FREE);
    if (!bev) {
        fprintf(stderr, "Error constructing bufferevent!");
        event_base_loopbreak(base);
        return;
    }
    // 设置回调
    bufferevent_setcb(bev, conn_readcb, conn_writecb, conn_eventcb, NULL);
    // 设置读写事件 能回调
    bufferevent_enable(bev, EV_WRITE | EV_READ);

    // 给 fd 发送消息
    bufferevent_write(bev, MESSAGE, strlen(MESSAGE));
}

static void
conn_writecb(struct bufferevent *bev, void *user_data)
{
    printf("触发了 写回调\n");
    struct evbuffer *output = bufferevent_get_output(bev);
    if (evbuffer_get_length(output) == 0) {
        printf("flushed answer\n");
        // 释放节点，自动关闭
        //bufferevent_free(bev);
    }
}

/**
 * 相比之下添加的部分
 * @param bev
 * @param user_data
 */
static void
conn_readcb(struct bufferevent *bev, void *user_data)
{
    char buf[1500] = "";
    int n = bufferevent_read(bev,buf, sizeof(buf));
    printf("%s",buf);
    bufferevent_write(bev,buf,n);
}

static void
conn_eventcb(struct bufferevent *bev, short events, void *user_data)
{
    if (events & BEV_EVENT_EOF) {
        printf("Connection closed.\n");
    } else if (events & BEV_EVENT_ERROR) {
        printf("Got an error on the connection: %s\n",
               strerror(errno));/*XXX win32*/
    }
    /* None of the other events can happen here, since we haven't enabled
     * timeouts */
    bufferevent_free(bev);
}

static void
signal_cb(evutil_socket_t sig, short events, void *user_data)
{
    struct event_base *base = user_data;
    struct timeval delay = { 2, 0 };

    printf("Caught an interrupt signal; exiting cleanly in two seconds.\n");

    event_base_loopexit(base, &delay);
}
